Array to XML Conversion using PHP

39

<?php
$input_array = array(
    'article' => array(
        array(
            'title' => 'Favorite Star Rating with jQuery',
            'link' => 'https://phppot.com/jquery/dynamic-star-rating-with-php-and-jquery/',
            'description' => 'Doing favorite star rating using jQuery Displays HTML stars.'
        ),
        array(
            'title' => 'PHP RSS Feed Read and List',
            'link' => 'https://phppot.com/php/php-simplexml-parser/',
            'description' => 'simplexml_load_file() function is used for reading data from XML.'
        )
    )
);

$xml = new DOMDocument();

$rootNode = $xml->appendChild($xml->createElement("items"));

foreach ($input_array['article'] as $article) {
    if (! empty($article)) {
        $itemNode = $rootNode->appendChild($xml->createElement('item'));
        foreach ($article as $k => $v) {
            $itemNode->appendChild($xml->createElement($k, $v));
        }
    }
}

$xml->formatOutput = true;

$backup_file_name = 'file_backup_' . time() . '.xml';
$xml->save($backup_file_name);

header('Content-Description: File Transfer');
header('Content-Type: application/xml');
header('Content-Disposition: attachment; filename=' . basename($backup_file_name));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($backup_file_name));
ob_clean();
flush();
readfile($backup_file_name);
exec('rm ' . $backup_file_name);
?>

Comments

Submit
0 Comments